import React, { PureComponent } from 'react';
import { Table, Button, message, Card, Icon, Divider, Popconfirm, Form, Modal, Input, Upload } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import styles from '../../Repair.less';
import Ellipsis from '@/components/Ellipsis';
import { baseUrl } from '../../../../services/baseUrl';
import { getAuthority } from '@/utils/authority';
import RenderAuthorized from '@/components/Authorized';
const Authorized = RenderAuthorized(getAuthority());  
const FormItem = Form.Item;
@Form.create()
@connect(({ assessment, loading,global}) => ({
  currentUrl:global.currentUrl,
  elementAuth:global.elementAuth,
  chechedkCompanyChildren : assessment.chechedkCompanyChildren,
  Checkfiles              : assessment.Checkfiles,
  loading                 : loading.effects['assessment/fetchGetChechedkCompanyChildren']
}))
export default class AssessChildList extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      fileVisible: false,
      id: null
    };
    this.dispatch = this.props.dispatch;
    this.routeParams = this.props.match.params;
  }
  returnColumn = () => {
    return [
      {
        title: '序号',
        dataIndex: 'Id',
        render: (text, record, index) => `${index + 1}`,
        width: 20,

      },
      // {
      //   title: '年份',
      //   width: 60,
      //   dataIndex: 'nf',
      // },
      // {
      //   title: '季度',
      //   width: 60,
      //   dataIndex: 'yf',
      // },
      {
        title: '考核指标',
        width: 60,
        dataIndex: 'khzb',
        render: (text, record) =>
          <Ellipsis length={6} tooltip>
            {text}
          </Ellipsis>
      },
      {
        title: '指标详解',
        width: 200,
        dataIndex: 'zbxj',
        render: (text, record) =>{
          return<Ellipsis tooltip>
            {text}
          </Ellipsis>
        }
      },
      {
        title: '实际扣分',
        width: 20,
        dataIndex: 'zbkf',
      },
      {
        title: '考核人员',
        width: 20,
        dataIndex: 'khryxm',
      },
      {
        title: '考核时间',
        width: 40,
        dataIndex: 'khsj',
        render: (text, record) =>
          <>{text ? moment(text).format('YYYY-MM-DD') : null}</>
      },
      {
        title: '备注',
        width: 60,
        dataIndex: 'bz',
        render: (text, record) =>
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
      },
      {
        title: '操作',
        key: 'action',
        width: 90,
        render: (text, record) =>
          <>
          <Authorized authority={this.props.elementAuth['edit']}>
            <a href="javascrips:;"
              onClick={() => {

                this.setState({ visible: true }, () => {
                  this.props.form.setFieldsValue({ bz: record.bz });
                  this.props.form.setFieldsValue({ id: record.id });
                });
              }}
            >
              <Icon type="edit" />

              编辑
                </a></Authorized>
            <Divider type="vertical" />
            <a href="javascrips:;"
              onClick={() => {

                this.setState({ fileVisible: true });
                this.setState({ id: record.id });
                this.fetchGetCheckfiles({id:record.id});
              }}
            >
              <Icon type="file-text" />

              文件管理
                </a>
            <Divider type="vertical" />
            <Authorized authority={this.props.elementAuth['delete']}>
            <Popconfirm title="确定删除?" onConfirm={() => { this.deleteCheckData({ id: record.id }) }}>
              <a href="javascrips:;"
              >
                <Icon type="delete" />
                删除
                </a>
            </Popconfirm></Authorized>
          </>
      },
    ]

  }
  returnFileCol=()=>{
    return [
      {
        title: '序号',
        dataIndex: 'Id',
        render: (text, record, index) => `${index + 1}`,
        width: 50,

      },
      {
        title: '文件名称',
        width: 100,
        dataIndex: 'wjmc',
        render:(text,record)=>{
          
           let arr = record.wjlj.split("/");
           return arr[5];
        }
      },
      {
        title: '文件类型',
        width: 100,
        dataIndex: 'wjhz',
     
      },
      {
        title: '操作',
        key: 'action',
        width: 90,
        render: (text, record) =>
          <>
          <Authorized authority={elementAuth['download']}>
            <a href="javascrips:;"
              onClick={() => {
                window.open(`mlapi/${record.wjlj}`);
              }}
            >
              <Icon type="edit" />
              下载
                </a>
                </Authorized>
            <Divider type="vertical" />
            <Authorized authority={elementAuth['delete']}>
            <Popconfirm title="确定删除?" onConfirm={() => { this.DeleteFile({ id: record.id }) }}>
              <a href="javascrips:;"
              >
                <Icon type="delete" />
                删除
                </a>
            </Popconfirm> </Authorized>
          </>
      },
    ]
  }
  submitAddValues = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.editCheckData({ id: values.id, bz: values.bz });
      }
    });
  }
  fetchGetChechedkCompanyChildren({ company = null, year = null, month = null, type = null, quota = null } = {}) {

    this.dispatch({
      type: 'assessment/fetchGetChechedkCompanyChildren',
      payload: {
        company: company,
        year: year,
        month: month,
        type: type,
        quota: quota
      },
      callback: response => {
        message.error.error('养护单位获取失败');
        console.log(response);
      },
    });
  }
  fetchGetCheckfiles=({id=null}={})=>{
    this.dispatch({
      type: 'assessment/fetchGetCheckfiles',
      payload: {
        id:id
      },
      callback: response => {
        message.error.error('文件列表获取失败');
        console.log(response);
      },
    });
  }
  DeleteFile({id=null}={}){
    const hide = message.loading('正在删除...', 0);
    this.dispatch({

      type: 'assessment/DeleteFile',
      payload: { id: id},
      callback: response => {
        hide();
        if (response.status) {
          message.success('删除成功');
          this.fetchGetCheckfiles({id:this.state.id });

        }
        else {
          message.error(response.ErrorMessage);
          console.log(response.ErrorMessage);
        }

      },
    });
  }
  editCheckData({ id = null, bz = null } = {}) {
    const hide = message.loading('正在编辑...', 0);
    this.dispatch({

      type: 'assessment/EditDetailData',
      payload: { id: id, bz: bz },
      callback: response => {
        hide();
        if (response.status) {
          message.success('编辑成功');
         
          this.fetchGetChechedkCompanyChildren({ company: this.routeParams.company, year: this.routeParams.year, month: this.routeParams.month, type: this.routeParams.type })

        }
        else {
          message.error(response.ErrorMessage);
          console.log(response.ErrorMessage);
        }

      },
    });


  }
  deleteCheckData({ id = null } = {}) {
    const hide = message.loading('正在删除...', 0);
    this.dispatch({

      type: 'assessment/DeleteDetailData',
      payload: { id: id },
      callback: response => {
        hide();
        if (response.status) {
          message.success('删除成功');
          this.fetchGetChechedkCompanyChildren({ company: this.routeParams.company, year: this.routeParams.year, month: this.routeParams.month, type: this.routeParams.type })

        }
        else {
          message.error(response.ErrorMessage);
          console.log(response.ErrorMessage);
        }

      },
    });


  }
  getAuth = () => {
    const { dispatch, currentUrl } = this.props;
    
    dispatch({
      type: 'global/fetchAuthorityElements',
      payload: { url: currentUrl },
    });
  };
  componentDidMount() {
    this.getAuth ();
    this.fetchGetChechedkCompanyChildren({ company: this.routeParams.company, year: this.routeParams.year, month: this.routeParams.month, type: this.routeParams.type })

  }
  render() {
    const _self = this;
    const { chechedkCompanyChildren, loading ,Checkfiles} = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 18 },
        sm: { span: 18 },
      },
    };
    const props = {
      name: 'file',
      action: `${baseUrl}/Check/UploadFile`,
      data: { id: this.state.id },
      showUploadList: false,
      multiple: true,
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功！`);
          _self.fetchGetCheckfiles({id:_self.state.id });
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败！`);
        }
      },
    };
    return (
      <Card
        title={
          <span style={{ borderLeft: '4px solid #3CB371', paddingLeft: '10px' }}>
            考核评价详情表
              {/* | {CheckedCompany?CheckedCompany.data[0].khbmmc:null} | {CheckedCompany?CheckedCompany.data[0].nf:null}年/{CheckedCompany?CheckedCompany.data[0].yf:null}季度 */}
          </span>
        }
        style={{ margin: '10px' }}
      >
        <Table
          className={styles.RepairTable}
          size="small"
          align={'center'}
          loading={loading}
          bordered
          dataSource={chechedkCompanyChildren ? chechedkCompanyChildren.data : null}
          columns={this.returnColumn()}
        />
        <Modal
          title="编辑"
          destroyOnClose
          visible={this.state.visible}
          onOk={() => {
            this.submitAddValues();
          }}
          onCancel={() => { this.setState({ visible: false }); }}
        ><Form {...formItemLayout}>
            <FormItem label="备注">
              {getFieldDecorator('bz', { initialValue: null })(
                <Input.TextArea row={4} placeholder={"备注"} />
              )}
            </FormItem>
            <FormItem label="备注" style={{ display: 'none' }}>
              {getFieldDecorator('id', { initialValue: null })(
                <Input.TextArea row={4} placeholder={"备注"} />
              )}
            </FormItem>
          </Form>
        </Modal>
        <Modal
          title="文件管理"
          destroyOnClose
          visible={this.state.fileVisible}
          onCancel={() => { this.setState({ fileVisible: false }); }}
          footer={null}
          width={700}
        >
          <Upload {...props}>
            <Button type="primary" style={{marginBottom:'20px'}}>
              <Icon type="upload" /> 上传
           </Button>
          </Upload>
          <Table
            className={styles.RepairTable}
            size="small"
            align={'center'}
            bordered
            dataSource={Checkfiles ? Checkfiles.data : null}
            columns={this.returnFileCol()}
            
          />
        </Modal>
      </Card>
    );
  }
}


